#include "widget.h"
#include "ui_widget.h"
#include <QNetworkDatagram>
const QString& SERVER_IP="127.0.0.1";
const quint16& PORT =8000;


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->pushButton->setDefault(true);
    this->setWindowTitle("客户端");
    socket=new QUdpSocket(this);
    connect(socket,&QUdpSocket::readyRead,this,&Widget::processResponse);

}

Widget::~Widget()
{
    delete ui;
}

//接收服务端数据包
void Widget::processResponse(){
    const QNetworkDatagram& serverDatagram=socket->receiveDatagram();
    //获取字节流数据
    QByteArray arr=serverDatagram.data();
    //转化为字符串
    QString serverdata=QString::fromUtf8(arr);
    //添加到文本框中
    ui->listWidget->addItem("服务端说: "+serverdata);
}


void Widget::on_pushButton_clicked()
{
    QString str=ui->lineEdit->text();
    if(!str.isEmpty()){
    QNetworkDatagram resquestDatagram(str.toUtf8(),QHostAddress(SERVER_IP),PORT);
    //向服务端发送数据报
    socket->writeDatagram(resquestDatagram);

    //把发送的请求添加到列表框中
    ui->listWidget->addItem("客户端说: "+str);
    //清空客户端内容
    ui->lineEdit->setText("");
    }
}
